package com.woniuxy.movice.service.imp;

import java.util.List;

import org.springframework.stereotype.Service;

import com.woniuxy.movice.dto.Round;
import com.woniuxy.movice.dto.RoundDate;
import com.woniuxy.movice.mapper.RoundMapper;
import com.woniuxy.movice.service.RoundService;

import lombok.Data;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.joda.time.Instant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import com.woniuxy.movice.entity.Rounds;
import com.woniuxy.movice.exception.RoundException;
import com.woniuxy.movice.util.EmptyUtil;

@Data
@Service
public class RoundServiceImp implements RoundService {
	
	private final static String NOTEXIST="场次不存在";//场次不存在
	private final static String HAVEFINISH="该场次已结束放映";//场次不存在

	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	@Autowired
	private RoundMapper roundMapper;
	
	@Override
	public List<Round> showRound(Round round) {
		return roundMapper.findRoundByMidAndYid(round);
	}
	
	@Override
	public Rounds getSetsInfo(Integer id) {
		Object redisResult=redisTemplate.opsForValue().get("Round"+id);
		//场次不为空，返回redis结果
		if(!EmptyUtil.isEmpty(redisResult)){
			if(NOTEXIST.equals(redisResult)){
				throw new RoundException(NOTEXIST);
			}
			if(HAVEFINISH.equals(redisResult)){
				throw new RoundException(HAVEFINISH);
			}
			return (Rounds)redisResult;
		}
		Rounds round=roundMapper.findRoundById(id);
		//若在数据库查询不到对应场次信息，抛出异常并更新到redis中
		if(EmptyUtil.isEmpty(round)){
			redisTemplate.opsForValue().set("Round"+id, NOTEXIST,1,TimeUnit.MINUTES);
			throw new RoundException(NOTEXIST);
		}
		//结束时间早于当前时间
		if(round.getPend().compareTo(new Instant().toDate())<0){
			redisTemplate.opsForValue().set("Round"+id, HAVEFINISH,1,TimeUnit.MINUTES);
			throw new RoundException(HAVEFINISH);
		}
		//其他情况可以选座
		long destroyTime=round.getPend().getTime()-new Date().getTime();
		redisTemplate.opsForValue().set("Round"+round.getId(), round,destroyTime,TimeUnit.MILLISECONDS);
		return round;
	}

	@Override
	public int updateLayout(Integer id,String seats) {
		return roundMapper.updateLayout(id,seats);
	}

	@Override
	public Round findRoundByCid(Integer cid) {
		return roundMapper.findRoundByCid(cid);
	}

	@Override
	public List<RoundDate> showRoundDate(Round round) {
		return roundMapper.showRoundDate(round);
	}

}
